package com.iw.adoms.action;

import com.iw.adoms.entity.Brand;
import com.iw.adoms.entity.Department;
import com.iw.adoms.service.BrandService;
import com.iw.adoms.service.DepartmentService;
import com.iw.core.orm.PageData;
import com.iw.core.security.entity.Users;
import com.iw.core.utils.WebUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/adoms/brand")
public class BrandAction {
    @Resource
    private BrandService brandService;
    @Resource
    private DepartmentService departmentService;

    @RequestMapping("/list")
    public ModelMap list(HttpServletRequest request) {
        PageData<Brand> pageData = new PageData<Brand>();
        // 给pageData设置参数
        WebUtils.setPageDataParameter(request, pageData);
        pageData = brandService.find(pageData);

        return new ModelMap(pageData);
    }

    @RequestMapping("/myBrands")
    public ModelMap myBrands(HttpServletRequest request, Model model) {
        PageData<Brand> pageData = new PageData<Brand>();
        // 给pageData设置参数
        WebUtils.setPageDataParameter(request, pageData);
        Integer did = getCurrentUser(request).getDepartment().getId();
        pageData.getPagination().setPageSize(10000);
        pageData = brandService.find(pageData);
        Set<Brand> myBrands = new HashSet<Brand>();
        for (Brand b : pageData.getResult()) {
            Set<Department> departs = b.getDepartment();
            for (Department d : departs) {
                if (d.getId().equals(did)) {
                    myBrands.add(b);
                }
            }
        }
        model.addAttribute("myBrands", myBrands);
        return new ModelMap(pageData);
    }

    @RequestMapping("/agentList")
    public ModelMap agentList(HttpServletRequest request) {
        PageData<Brand> pageData = new PageData<Brand>();
        // 给pageData设置参数
        WebUtils.setPageDataParameter(request, pageData);
        pageData = brandService.find(pageData);
        return new ModelMap(pageData);
    }

    @RequestMapping(value = "/newAgent")
    public String addAgentForm(Model model) {
        List<Brand> brandList = brandService.findAll();
        model.addAttribute("brandList", brandList);
        commonAgentModel(model);
        return "/adoms/brand/agentInput";
    }

    private void commonAgentModel(Model model) {
        List<Department> departmentList = departmentService.findAll();
        model.addAttribute("departmentList", departmentList);
    }

    @RequestMapping(value = "/editAgent/{id}")
    public String editAgentForm(@PathVariable("id") Integer id, Model model) {
        Brand brand = brandService.find(id);
        model.addAttribute(brand);
        commonAgentModel(model);
        return "/adoms/brand/agentInput";
    }

    @RequestMapping(value = "/inputDetail/{did}")
    public String inputDetail(@PathVariable("did") Integer did, Model model) {
        List<Brand> brands = new ArrayList<Brand>();
        if (did == null || did == 0) {
            brands = brandService.findAll();
        } else {
            brands = brandService.findBrandByDepartmentID(did);
        }

        if (brands != null) {
            model.addAttribute("brands", brands);
        }

        return "/adoms/brand/inputDetail";
    }

    @RequestMapping(value = "/brands/{did}")
    @ResponseBody
    public List<Brand> brands(@PathVariable("did") Integer did) {

        List<Brand> brands = new ArrayList<Brand>();
        if (did == null || did == 0) {
            brands = brandService.findAll();
        } else {
            brands = brandService.findBrandByDepartmentID(did);
        }

        return brands;

    }

    @RequestMapping(value = "/saveAgent", method = RequestMethod.POST)
    public String saveAgent(Brand brand, HttpServletRequest request) {
        brand = brandService.find(brand.getId());
        String[] departmentIds = request.getParameterValues("department.id");
        Set<Department> department = new HashSet<Department>();
        for (String id : departmentIds) {
            try {
                Department d = departmentService.find(Integer.parseInt(id));
                department.add(d);
            } catch (Exception e) {
            }
        }
        brand.setDepartment(department);
        brandService.update(brand);

        return "redirect:/adoms/brand/agentList";// 重定向
    }

    @RequestMapping(value = "/new")
    public String addForm(Model model) {
        return "/adoms/brand/input";
    }

    @RequestMapping(value = "/repeat")
    @ResponseBody
    public boolean repeat(String value, Integer id, String property) {
        try {
            List<Brand> brands = brandService.findList(property, value);
            if (brands != null && brands.size() > 0) {
                if (id != 0) {
                    Brand b = brandService.find(id);
                    if (property.equals("name") && !b.getName().equals(value)) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @RequestMapping(value = "/edit/{id}")
    public String editForm(@PathVariable("id") Integer id, Model model) {
        Brand brand = brandService.find(id);
        model.addAttribute(brand);
        return "/adoms/brand/input";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Brand brand) {
        if (brand.isNew()) {
            brandService.save(brand);
        } else {
            brandService.update(brand);
        }

        return "redirect:/adoms/brand/list";// 重定向
    }

    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        brandService.delete(id);
        return "redirect:/adoms/brand/list";// 重定向
    }

    @RequestMapping(value = "/visible/{id}")
    public String visible(@PathVariable("id") Integer id) {
        brandService.visible(id);
        return "redirect:/adoms/brand/list";// 重定向
    }

    @RequestMapping(value = "/unVisible/{id}")
    public String unVisible(@PathVariable("id") Integer id) {
        brandService.unVisible(id);
        return "redirect:/adoms/brand/list";// 重定向
    }

    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
    }

    private Users getCurrentUser(HttpServletRequest request) {
        Users user = (Users) request.getSession().getAttribute("USER");
        return user;
    }

}
